<?php
/**
 * 关键字分类
 */
namespace App\Http\Controllers\Admin;
use App\Common\Excel\ExcelSpout;
use App\Common\Utill\OperationLog;
use App\Common\Utill\Utills;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Service\CategoryService;
use App\Service\WebsitesService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class CategoryController extends Controller
{
    public function index()
    {
        $websiteData = WebsitesService::getWebsiteData();
        return view('admin.category.index')->with('websiteData', $websiteData);
    }

    /**
     * 分类列表数据
     * @return void
     */
    public function listData(Request $request)
    {
        $num = $request->input('limit',self::ADMIN_PAGE_NUM);
        $server = new CategoryService();
        $result = $server->getListData($request,$num);
        return Utills::resultData($result);
    }

    /**
     * 添加数据展示
     */
    public function createForm()
    {
        $websiteData = WebsitesService::getWebsiteData(1);
        return view('admin.category.create')->with('websiteData', $websiteData);
    }

    /**
     * 添加数据保存
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $data = $request->all();
        $server = new CategoryService();
        $result = $server->create($data);
        return Utills::resultData($result);
    }

    /**
     * 编辑展示
     * @return
     */
    public function editForm(Request $request)
    {
        $id = $request->input('id',0);
        $data = Category::where(['id' => $id])->first();
        //网站信息
        $websiteData = WebsitesService::getWebsiteData();
        return view('admin.category.edit')->with('data', $data)->with('websiteData', $websiteData);
    }

    /**
     * 编辑保存
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request)
    {
        $data = $request->all();
        $server = new CategoryService();
        $result = $server->update($data);
        return Utills::resultData($result);
    }

    /*
   * 释放
   */
    public function release(Request $request)
    {
        if (!$request->input('id')) {
            return $this->error('删除失败');
        }
        $id = $request->input('id');
        $server = new CategoryService();
        $result = $server->release($id);
        return Utills::resultData($result);
    }

    /*
    * 删除
    */
    public function delete(Request $request)
    {
        if (!$request->input('id')) {
            return $this->error('删除失败');
        }
        $id = $request->input('id');
        $server = new CategoryService();
        $result = $server->delOne($id);
        return Utills::resultData($result);
    }

    /*
     *全部删除
     */
    public function deleteAll(Request $request)
    {
        $idArr = $request->input('idList',"");
        $server = new CategoryService();
        $result = $server->delAll($idArr);
        return Utills::resultData($result);
    }

    /**
     * 分类导入-展示
     * @return void
     */
    public function importExcel()
    {
        return view('admin.category.import');
    }

    /**
     * 分类导入数据
     * @return void
     */
    public function importExcelData(Request $request)
    {
        $file = $request->file('excelFile');
        if(!$file){
            return back()->withErrors(['error' => ['请上传文件']]);
        }
        $originName = $file->getClientOriginalName();
        $extension  = $file->getClientOriginalExtension();
        $newFileName = date('ymdHis').rand(1000,99999).'.'.$extension;
        Log::info("分类导入:".$originName.",新的文件名:".$newFileName);
        $filePath = $file->storeAs('excel',$newFileName,'uploads');
        //获取文件的路径
        $filePath = public_path("/uploads/".$filePath);
        //获取文件的内容
        $excel = new ExcelSpout();
        $importData = $excel->import($filePath,2);
        $newImportData = [];
        //后台用户
        $adminId = CategoryService::getAdminId();
        //获取网站
        $getWebsiteData = WebsitesService::getWebsiteData(2,1);
        if(!$getWebsiteData){
            return back()->withErrors(['error' => ['请先选择网站']]);
        }
        $getWebsiteData = array_flip($getWebsiteData);
        $isErrorStatus = 0;
        foreach ($importData as $key=>$val){
            if(!isset($val[1])){
                $isErrorStatus = 1;
                break;
            }
            if(!isset($getWebsiteData[$val[1]])){
                $isErrorStatus = 1;
                break;
            }
            $newImportData[$key]['category_name'] = $val[0];
            $newImportData[$key]['website_id'] = $getWebsiteData[$val[1]];
            $newImportData[$key]['admin_id'] = $adminId;
            $newImportData[$key]['type'] = 1;
            $newImportData[$key]['is_del'] = 1;
            $newImportData[$key]['created_at'] = date('Y-m-d H:i:s');
        }
        if($isErrorStatus){
            return back()->withErrors(['error' => ['网站名称不正确']]);
        }
        //
        $newImportDataArr = array_chunk($newImportData,3);
        foreach ($newImportDataArr as $kk=>$vv){
           DB::table('pd_category')->insert($vv);
        }
        OperationLog::record(1,'关键词管理-导入');
        return redirect()->route('admin.category.importExcel')->with("statusClose","操作成功");
    }



}
